﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Diagnostics;
using System.Threading;
using Util;
using TransferModel = YLPublicService.TransferModel;
using YLServerInterface.ServerConfig;

namespace YLServerInterface.FunctionalClass
{
    /// <summary>
    /// 在一个已经整备好的环境下生成exe
    /// 目录下包括 图片和模板文件
    /// </summary>
    public class FlashExeMaker
    {

        public string PhotosFolder { get; set; }
        public string TemplateProjectFilePath { get; private set; }
        // public Template Template { get; private set; }
        private string yazhiExeFilePath;
        // private TransferModel.WorkItem2ServerUser workItem;
        private static YLServerConfig config = YLServerConfig.GetConfig();
        #region 控制雅致打包
        //#region 定义雅致程序界面按钮名称，供WindowsAPI寻找元素使用
        //static readonly string MakeBtnLiteral = config.YaZhiMakeBtnName;
        //static readonly string YesBtnLiteral = config.YaZhiDialogBoxYesBtn;
        ///// <summary>
        ///// 雅致已经生成了文件，再次生成的时候会弹出是否覆盖窗口，定义窗口名称
        ///// </summary>
        //static readonly string ReCheckWindowLiteral = "操作确认";


        #region 声明调用的Windows API函数
        [DllImport("User32.dll")]
        public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);
        [DllImport("User32.dll")]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll")]
        static extern int SendMessage(IntPtr hWnd, int msg, int wParam, StringBuilder lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
        #endregion

        #region 定义Windows按钮的消息常量
        const int WM_LBUTTONDOWN = 0x201;
        const int WM_LBUTTONUP = 0x0202;
        const int WM_GETTEXT = 0x000D;
        const int WM_SETTEXT = 0x000C;
        const int WM_KEYDOWN = 0x0100;
        const int bufferLen = 1024;

        // sample, u should use spy++ to find windows class name and control class name 
        #endregion

        #region 新实现在Util项目中
        ///// <summary>
        ///// 按下雅致打包makeEXE按钮
        ///// </summary>
        ///// <param name="hWndMake"></param>
        ///// <returns></returns>
        //static bool ClickMakeExe(IntPtr hWndMake)
        //{

        //    if (hWndMake != IntPtr.Zero)
        //    {
        //        #region 按下MAKE按钮，以及处理可能弹出的覆盖已生成文件对话框
        //        while (false == PostMessage(hWndMake, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero))
        //            ;//Console.WriteLine("makeExe mouseDown");
        //        while (false == PostMessage(hWndMake, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero))
        //            ;//Console.WriteLine("makeExe mouseUp");
        //        IntPtr hwndDialog;
        //        hwndDialog = FindWindow(null, ReCheckWindowLiteral);
        //        for (int i = 0; i < 1000; i++) //如果存在生成好的文件，雅致程序会提示是否覆盖。
        //        {
        //            hwndDialog = FindWindow(null, ReCheckWindowLiteral);
        //        }

        //        if (hwndDialog != IntPtr.Zero)//如果出现是否覆盖窗口，那么就发消息点是。
        //        {
        //            IntPtr hwndYesBtn;
        //            do
        //            {
        //                hwndYesBtn = FindWindowEx(hwndDialog, IntPtr.Zero, "Button", YesBtnLiteral);
        //            } while (hwndYesBtn == IntPtr.Zero);
        //            if (hwndYesBtn != IntPtr.Zero)
        //            {
        //                while (false == PostMessage(hwndYesBtn, WM_LBUTTONDOWN, IntPtr.Zero, IntPtr.Zero)) ;
        //                while (false == PostMessage(hwndYesBtn, WM_LBUTTONUP, IntPtr.Zero, IntPtr.Zero)) ;
        //            }
        //            //else
        //            //{
        //            //    Console.WriteLine("yesBtn null");
        //            //}
        //        }
        //        //else
        //        //{
        //        //    Console.WriteLine("dialog pointer null");
        //        //}
        //        return true;
        //        #endregion
        //    }
        //    return false;
        //} 

        ///// <summary>
        ///// 雅致打包文件
        ///// </summary>
        //static void YazhiMakeFile()
        //{
        //    IntPtr hwndWin = FindWindow("TfrmMain", null);
        //    if (hwndWin.Equals(IntPtr.Zero) == false)
        //    {
        //        IntPtr hwndMakeBtn = FindWindowEx(hwndWin, IntPtr.Zero, "Tbutton", MakeBtnLiteral);
        //        ClickMakeExe(hwndMakeBtn);
        //    }
        //}
        //
        #endregion

        #endregion

        public FlashExeMaker()
        {
            this.yazhiExeFilePath = config.YaZhiExePath;
        }
        //public FlashExeMaker(TransferModel.WorkItem2ServerUser workItem)
        //{

        //    this.yazhiExeFilePath = config.YaZhiExePath;
        //    this.workItem = workItem;
        //}

        /// <summary>
        /// 生成exe
        /// </summary>
        /// <param name="photosFolder"></param>
        /// <param name="templateProjectFilePath"></param>
        /// <returns></returns>
        public Tuple<bool, string> MakeExe(string yaZhiProjectFilePath)
        {
            try
            {
                var process = runYazhiexe(yaZhiProjectFilePath);
                #region 等待一段时间，让程序绘制自身，如果时间不够下一步按make 按钮无法成功
                Thread.Sleep(Int32.Parse(config.YaZhiRenderSelftTime));
                #endregion
                //点击生成
                YazhiOP.ClickMakeBtn(config.YaZhiMakeBtnName);

                #region 等待一段时间 如果为可能出现的重复生成对话框
                Thread.Sleep(Int32.Parse(config.YaZhiDialogBoxRenderSelftTime));
                #endregion
                YazhiOP.PassCheckBoxIFExist(config.YaZhiDialogBoxYesBtn);

                #region 等待make 时间，如果不够需要配置
                Thread.Sleep(Int32.Parse(config.YaZhiPrepareMakeTime));
                //进程在生成文件所以会无响应，前面等待时间是让进程有足够的时间进入无响应状态（生成文件）
                //while (!process.Responding)
                //    ;
                #endregion
                var makeRet = YazhiOP.GetResultText();
                process.Kill();
                //当没有输出，或者有跳过，那么就返回失败。
                return Tuple.Create(
                    makeRet.Item1 > 0 &&
                    (!makeRet.Item2.Contains("已跳过")),
                    makeRet.Item2);
            }
            catch (Exception ex)
            {
                return Tuple.Create(false, ex.Message);
            }
        }

        //public Tuple<bool, string> MakeExe()
        //{
        //    FileManager fileM = new FileManager();

        //    if (fileM.PrepareWorkItem(workItem))
        //    {
        //        try
        //        {
        //            var process = runYazhiexe(fileM.YazhiProjectName);
        //            #region 等待一段时间，让程序绘制自身，如果时间不够下一步按make 按钮无法成功
        //            Thread.Sleep(Int32.Parse(config.YaZhiRenderSelftTime));
        //            #endregion
        //            //点击生成
        //            YazhiOP.ClickMakeBtn(config.YaZhiMakeBtnName);

        //            #region 等待一段时间 如果为可能出现的重复生成对话框
        //            Thread.Sleep(Int32.Parse(config.YaZhiDialogBoxRenderSelftTime));
        //            #endregion
        //            YazhiOP.PassCheckBoxIFExist(config.YaZhiDialogBoxYesBtn);

        //            #region 等待make 时间，如果不够需要配置
        //            Thread.Sleep(Int32.Parse(config.YaZhiPrepareMakeTime));
        //            //进程在生成文件所以会无响应，前面等待时间是让进程有足够的时间进入无响应状态（生成文件）
        //            //while (!process.Responding)
        //            //    ;
        //            #endregion
        //            var makeRet = YazhiOP.GetResultText();
        //            process.Kill();
        //            //当没有输出，或者有跳过，那么就返回失败。
        //            return Tuple.Create(
        //                makeRet.Item1 > 0 &&
        //                (!makeRet.Item2.Contains("已跳过")),
        //                makeRet.Item2);
        //        }
        //        catch (Exception ex)
        //        {
        //            return Tuple.Create(false, ex.Message);
        //        }
        //    }
        //    return Tuple.Create(false, "FileManager. PrepareWorkItem失败");
        //}

        private static Process runYazhiexe(string yazhiProjectName)
        {
            var processes = Process.GetProcessesByName("yazhi");

            if (processes != null)
            {
                foreach (var p in processes)
                {
                    p.Close();
                }
            }
            return Process.Start(config.YaZhiExePath, yazhiProjectName);
        }
        /// <summary>
        /// 预热
        /// </summary>
        static FlashExeMaker()
        {

            var proc = Process.Start(config.YaZhiExePath);
            proc.WaitForExit(Int32.Parse(config.YaZhiRenderSelftTime));
            proc.Kill();
        }
    }
}